package com.github.filters;

import com.github.CommonConstant;
import com.github.session.SObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author  Crab2Died
 */
public class LoginFilter implements Filter {

    private static Logger logger = LoggerFactory.getLogger(LoginFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        logger.debug("init LoginFilter class ...");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
                         FilterChain filterChain)
            throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String reqURI = request.getRequestURI();

        SObject sObject = (SObject) request.getSession().getAttribute(CommonConstant.USER_LOGIN_SESSION);

        if (!reqURI.endsWith("login") && !reqURI.endsWith(".css") && !reqURI.endsWith(".js")
                && !reqURI.endsWith(".png") && !reqURI.endsWith(".jpg") && !reqURI.endsWith("ico")) {
            if (null == sObject) {
                //request.getRequestDispatcher("/").forward(request, response);
                response.sendRedirect("login");
                logger.error(reqURI + " the request intercepted!");
                return;
            }
        }
        filterChain.doFilter(request, response);

    }

    @Override
    public void destroy() {
        logger.debug("destroy LoginFilter class ...");
    }
}
